package com.freeter.config;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.freeter.common.utils.SpringContextUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Component
public class MyMetaObjectHandler extends MetaObjectHandler {

	protected final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

	@Override
	public void insertFill(MetaObject metaObject) {
		setFieldValByName("createTime", new Date(), metaObject);
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//操作用户名
			Long userId = (Long) request.getAttribute("userId");
			if(userId != null) {
				setFieldValByName("createBy",userId,metaObject);
			}
		} catch (UnavailableSecurityManagerException e) {
			System.out.println("定时任务不能由shiro管理，所以执行shiro方法会报错");
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {

		setFieldValByName("updateTime", new Date(), metaObject);

		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//操作用户名
			Long userId = (Long) request.getAttribute("userId");
			if(userId != null) {
				setFieldValByName("updateBy",userId,metaObject);
			}
		} catch (UnavailableSecurityManagerException e) {
			System.out.println("定时任务不能由shiro管理,所以执行shiro方法会报错");
		}
	}

}
